<template>
  <div class="import-container">
    <input 
      type="file" 
      id="file-import" 
      accept=".csv" 
      style="display: none" 
      @change="handleFileImport"
    >
    <button @click="triggerFileImport" class="import-btn">
      📁 导入CSV数据
    </button>
    <span v-if="status" class="import-status" :class="statusType">
      {{ status }}
    </span>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// Emits定义
const emit = defineEmits(['data-imported', 'import-status-change'])

// 响应式状态
const status = ref('')
const statusType = ref('')

// 触发文件选择
const triggerFileImport = () => {
  document.getElementById('file-import').click()
}

// 处理文件导入
const handleFileImport = (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (file.type !== 'text/csv' && !file.name.endsWith('.csv')) {
    updateStatus('请选择CSV格式文件', 'error')
    return
  }

  updateStatus('正在导入数据...', 'loading')
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const csvData = e.target.result
      const parsedData = parseCSV(csvData)
      
      // 发出数据导入事件
      emit('data-imported', parsedData)
      updateStatus('数据导入成功', 'success')
      
      // 重置文件输入，允许重新选择同一个文件
      event.target.value = ''
      
      // 3秒后清除状态信息
      setTimeout(() => {
        clearStatus()
      }, 3000)
      
    } catch (error) {
      console.error('导入文件失败:', error)
      updateStatus('数据导入失败', 'error')
    }
  }
  
  reader.onerror = () => {
    updateStatus('读取文件失败', 'error')
  }
  
  reader.readAsText(file)
}

// 解析CSV数据
const parseCSV = (csvString) => {
  const lines = csvString.split('\n')
  const headers = lines[0].split(',').map(h => h.trim())
  
  const data = []
  
  for (let i = 1; i < lines.length; i++) {
    if (!lines[i].trim()) continue // 跳过空行
    
    const values = lines[i].split(',').map(v => v.trim())
    const item = {}
    
    headers.forEach((header, index) => {
      if (index < values.length) {
        item[header.toLowerCase().replace(/\s+/g, '_')] = values[index]
      }
    })
    
    data.push(item)
  }
  
  return data
}

// 更新状态信息
const updateStatus = (message, type) => {
  status.value = message
  statusType.value = type
  emit('import-status-change', { message, type })
}

// 清除状态信息
const clearStatus = () => {
  status.value = ''
  statusType.value = ''
  emit('import-status-change', { message: '', type: '' })
}
</script>

<style scoped>
.import-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.import-btn {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.import-btn:hover {
  background-color: #45a049;
}

.import-status {
  font-size: 14px;
  padding: 5px 10px;
  border-radius: 4px;
  font-weight: 500;
}

.import-status.loading {
  background-color: #e3f2fd;
  color: #1976d2;
}

.import-status.success {
  background-color: #e8f5e8;
  color: #2e7d32;
}

.import-status.error {
  background-color: #ffebee;
  color: #c62828;
}

/* 深色模式下的样式 */
:global(.dark-mode) .import-container {
  background-color: #2d2d2d;
}

:global(.dark-mode) .import-status.loading {
  background-color: #1a237e;
  color: #90caf9;
}

:global(.dark-mode) .import-status.success {
  background-color: #1b5e20;
  color: #81c784;
}

:global(.dark-mode) .import-status.error {
  background-color: #b71c1c;
  color: #ffcdd2;
}
</style>